package com.imisty.oa.controller;

import com.imisty.oa.biz.GlobalBiz;
import com.imisty.oa.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller("globalController")
public class GlobalController {

    @Autowired
    private GlobalBiz globalBiz;

    @RequestMapping("to_login")
    public String toLogin(){
        return "login";
    }

    /**
     * 这里登录可以使用Employee 对象，然后界面用modelAttribute属性
     * @param session 声明HttpSrssion SpringMVC框架会自动注入
     * @param sn
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public String login(HttpSession session , @RequestParam("sn") String sn, @RequestParam String password){
        Employee employee = globalBiz.login(sn,password);
        if (employee == null){
            return "redirect:to_login";
        }
        session.setAttribute("employee",employee);
        return "redirect:self";
    }

    /**
     *
     * 跳转到个人信息界面
     * @return
     */
    @RequestMapping("/self")
    public String self(){
        //这里千万不可以用重定向,不然会导致无限次的请求自身（不是页面而是请求），出现严重逻辑错误，导致浏览器提示处对象次数过多
        //return  "redirect:self";
        return "self";
    }

    /**
     * 退出登录操作session
     * @param session
     * @return
     */
    @RequestMapping("/quit")
    public String quit(HttpSession session){
        //移除session里面的员工对象或者将session的员工置空
        session.setAttribute("employee",null);
        return "redirect:to_login";
    }

    @RequestMapping("/to_change_password")
    public String toChangePassword(){
        return "change_password";
    }

    @RequestMapping("/change_password")
    public String changePassword(HttpSession session,@RequestParam String old,@RequestParam String new1,@RequestParam String new2){
        //  两次输入的密码一致并且旧密码和session中的密码一致才进行修改
        if (new1.equals(new2)){
            Employee employee = (Employee) session.getAttribute("employee");
            //
            if (employee.getPassword().equals(old)){
                employee.setPassword(new1);
                globalBiz.changePassword(employee);
                session.setAttribute("employee",employee);
                return "redirect:self";
            }
        }
        //重新去修改密码
        return "redirect:to_change_password";
    }
}
